package com.cloudwise.monitoring_system.util;

import com.cloudwise.monitoring_system.entity.OperLog;
import com.cloudwise.monitoring_system.service.OperLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Reisen
 * @description: 监控接口调用工具类
 * @date 2021/6/3 11:39
 */
@Aspect
@Component
public class OperLogUtil {
    @Resource
    private OperLogService operLogService;
    /**
     * 监控接口调用
     * @param joinpoint
     */
    @AfterReturning(pointcut = "execution(* com.cloudwise.monitoring_system.service.mysqlService.impl.MonitorValueServiceImpl.queryAll*(..)) " +
            "|| execution(* com.cloudwise.monitoring_system.service.mysqlService.impl.MonitorEventServiceImpl.eventQueryAll*(..))" +
            "|| execution(* com.cloudwise.monitoring_system.service.mysqlService.impl.MonitorUnitServiceImpl.update*(..))")
    public void recordOperLog(JoinPoint joinpoint){
        OperLog operLog = new OperLog();
        String methodName = joinpoint.getSignature().getName();
        int bussinessType = BussinessConstants.type.DEFAULT;
        if (methodName.contains("eventQueryAll")){
            bussinessType=BussinessConstants.type.EVENT_QUERY;
        }else if (methodName.contains("queryAll")){
            bussinessType=BussinessConstants.type.MYSQL_QUERY;
        }else if (methodName.contains("update")){
            bussinessType=BussinessConstants.type.UPDATE;
        }
        //记录操作日志类型
        operLog.setType(bussinessType);

        String className = joinpoint.getTarget().getClass().getName();
        operLog.setMethod(className + "." + methodName);
        //获取HttpServletRequest
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取uri
        String requestURI = request.getRequestURI();
        operLog.setOperUrl(requestURI);
        //获取IP
        String remoteAddr = request.getRemoteAddr();
        operLog.setIp(remoteAddr);
        //操作时间
        operLog.setCreateTime(new Date());

        Object[] args = joinpoint.getArgs();

        if(args!=null&&args.length>0){
            operLog.setOperParam(args[0].getClass().getSimpleName());
        }
        //System.out.println(operLog);;
        operLogService.insert(operLog);
    }
}
